<?php

class PageController extends BackEndController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array(
                'allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('create', 'update', 'index', 'view', 'admin', 'delete', 'Up', 'Down'),
                'users' => array('admin'),),
            array(
                'deny', // deny all users
                'users' => array('*'),),);
    }

    /**
     * Displays a particular model.
     *
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => $this->loadModel($id),));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Page;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Page'])) {
            $limit = $this->getMaxUrut($_POST['Page']['top_halaman']);
            $_POST['Page']['urut_halaman'] = $limit['last_'] + 1;
            $model->attributes = $_POST['Page'];
            if ($model->save()) {
                $this->menuAdmin(1);
                app()->end();
            }
        }
        $this->render('create', array(
            'model' => $model,
            'pages' => $this->getListTop()));
    }

    protected function getMaxUrut($top_hal)
    {
        $db = app()->getDb();
        return $db->createCommand()->select("MAX(urut_halaman) as last_, MIN(urut_halaman) as first_")->from("{{page}}")
            ->where("top_halaman=:id and halaman_id!=1", array(":id" => $top_hal))->queryRow();
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Page'])) {
            if (($_POST['Page']['top_halaman'] != '') && ($_POST['Page']['top_halaman'] != $model->top_halaman)
            ) {
                $this->normalizeUrut($model->top_halaman, $model->urut_halaman);
                $limit = $this->getMaxUrut($_POST['Page']['top_halaman']);
                $_POST['Page']['urut_halaman'] = $limit['last_'] + 1;
            } else {
                $_POST['Page']['top_halaman'] = $model->top_halaman;
                $_POST['Page']['urut_halaman'] = $model->urut_halaman;
            }
            if (!$model->kategori_halaman) {
//                $_POST['Page']['isi_halaman'] = Encrypt($_POST['Page']['isi_halaman']);
//                $_POST['Page']['content'] = Encrypt($_POST['Page']['content']);
            }
            $model->attributes = $_POST['Page'];
            if ($model->save()) {
                $this->menuAdmin(1);
                app()->end();
            }
        }
        $this->render('update', array(
            'model' => $model,
            'pages' => $this->getListTop()));
    }

    protected function normalizeUrut($top, $urut)
    {
        $db = app()->getDb();
        $db->createCommand("update {{page}} set urut_halaman = (urut_halaman - 1) WHERE
            top_halaman = :top AND urut_halaman > :urut")->execute(array(':top' => $top, ':urut' => $urut));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     *
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
//        $model = $this->loadModel($id);
//        $this->normalizeUrut($model->top_halaman, $model->urut_halaman);
//        $model->delete();
        $this->DeleteMenu($id);
        //$this->menuAdmin(1);
    }

    protected function DeleteMenu($id)
    {
        $criteria = new CDbCriteria();
        $criteria->addCondition("top_halaman=$id");
        $criteria->addCondition("halaman_id!=1");
        $model = Page::model()->findAll($criteria);
        foreach ($model as $page) {
            $this->DeleteMenu($page->halaman_id);
        }
        $menu = $this->loadModel($id);
        $this->normalizeUrut($menu->top_halaman, $menu->urut_halaman);
        $menu->delete();
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('Page');
        $this->render('index', array(
            'dataProvider' => $dataProvider,));
    }

    /**
     * Manages all models.
     */
    protected function menuAdmin($id)
    {
        $arrhal = $this->getHalaman(1);
        $criteria = new CDbCriteria();
        $criteria->addCondition("top_halaman=$id");
        $criteria->addCondition("halaman_id!=1");
        $criteria->order = "urut_halaman";
        $model = Page::model()->findAll($criteria);
//        $criteria = new CDbCriteria;
//        $criteria->select = 'max(urut_halaman) AS maxColumn';
//        $model_max = CniHalaman::model()->findAll($criteria);
//        $max = $model_max['maxColumn'];
        $arrayDataProvider = new CArrayDataProvider($arrhal, array(
            'keyField' => 'halaman_id',));
        $this->render('admin', array(
            'model' => $model,
            'arrayDataProvider' => $arrayDataProvider,//'max' => $max,
//            'min' => 1
        ));
    }

    protected function getListTop()
    {
        $pages = $this->getHalaman(1, 0, "- ");
        $list[1] = 'Menu Item Root';
        foreach ($pages as $page) {
            $list[$page['halaman_id']] = $page['nama_halaman'];
        }
        return $list;
    }

    protected function getHalaman($id, $level = 0, $prefix = "|-")
    {
        $arrpage = array();
        $prefix_nama = '';
        for ($i = 0; $i < $level; $i++) {
            $prefix_nama .= $prefix;
        }
        $level++;
        $criteria = new CDbCriteria();
        $criteria->addCondition("top_halaman=$id");
        $criteria->addCondition("halaman_id!=1");
        $criteria->order = "urut_halaman";
        $model = Page::model()->findAll($criteria);
        $limit = $this->getMaxUrut($id);
        foreach ($model as $page) {
            $arrpage[] = array(
                'halaman_id' => $page['halaman_id'],
                'top_halaman' => $page['top_halaman'],
                'urut_halaman' => $page['urut_halaman'],
                'nama_halaman' => $prefix_nama . $page['nama_halaman'],
                'kategori_halaman' => $page['kategori_halaman'],
                'file_include' => $page['file_include'],
                'status_halaman' => $page['status_halaman'],
                'first' => $limit['first_'] === $page['urut_halaman'],
                'last' => $limit['last_'] === $page['urut_halaman'],);
            $child_page = $this->getHalaman($page['halaman_id'], $level, $prefix);
            foreach ($child_page as $page1) {
                $arrpage[] = $page1;
            }
        }
        return $arrpage;
    }

    public function actionAdmin($id)
    {
        $this->menuAdmin($id);
    }

    public function actionUp($id)
    {
        $this->movePage($id);
        $this->menuAdmin(1);
    }

    public function actionDown($id)
    {
        $this->movePage($id, false);
        $this->menuAdmin(1);
    }

    protected function movePage($id, $up = true)
    {
        $halaman = $this->loadModel($id);
        $urut_ = $halaman->urut_halaman;
        if ($up) $halaman->urut_halaman--; else
            $halaman->urut_halaman++;
        $criteria = new CDbCriteria();
        $criteria->addCondition("top_halaman=$halaman->top_halaman");
        $criteria->addCondition("urut_halaman=$halaman->urut_halaman");
        $criteria->addCondition("halaman_id!=1");
        $model = Page::model()->find($criteria);
        $model->urut_halaman = $urut_;
        $model->save();
        $halaman->save();
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     *
     * @param integer $id the ID of the model to be loaded
     *
     * @return Page the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model = Page::model()->findByPk($id);
        if ($model === null) throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     *
     * @param Page $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'page-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
